package booklib.view;

import java.awt.EventQueue;
import java.sql.Connection;
import java.sql.ResultSet;
import java.util.Vector;

import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;

import booklib.dao.BookDao;
import booklib.dao.BookTypeDao;
import booklib.model.Book;
import booklib.model.BookType;
import booklib.util.DbUtil;
import booklib.util.StringUtil;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JRadioButton;
import javax.swing.ButtonGroup;
import javax.swing.JTextArea;
import javax.swing.ImageIcon;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class BookManagerInterFrame extends JInternalFrame {
	private JTable bookTable;
	private JTextField s_bookNametxt;
	private JTextField s_authortxt;
	private DbUtil dbUtil=new DbUtil();
	private BookTypeDao bookTypeDao=new BookTypeDao();

	private BookDao bookDao=new BookDao();
	private JComboBox s_bookTypejcb;
	private JTextField idtxt;
	private JTextField bookNametxt;
	private final ButtonGroup buttonGroup = new ButtonGroup();
	private JTextField pricetxt;
	private JTextField authortxt;
	private JComboBox bookTypejcb;
	private JRadioButton manjrb;
	private JTextArea bookDesctxt;
	private JRadioButton femalejrb ;
	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					BookManagerInterFrame frame = new BookManagerInterFrame();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public BookManagerInterFrame() {
		setTitle("图书管理");
		setIconifiable(true);
		setClosable(true);
		setBounds(100, 100, 781, 657);
		
		JScrollPane scrollPane = new JScrollPane();
		
		JPanel panel = new JPanel();
		panel.setBorder(new TitledBorder(null, "\u641C\u7D22\u6761\u4EF6", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		
		JPanel panel_1 = new JPanel();
		panel_1.setBorder(new TitledBorder(null, "\u8868\u5355\u64CD\u4F5C", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		
		JButton btnNewButton_1 = new JButton("修改");
		btnNewButton_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				bookUpdateActionPerformed(e);
			}
		});
		btnNewButton_1.setIcon(new ImageIcon(BookManagerInterFrame.class.getResource("/images/Modify_16px_1060983_easyicon.net.png")));
		
		JButton button = new JButton("删除");
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {

				bookDeleteActionPerformed(e);
			}
		});
		button.setIcon(new ImageIcon(BookManagerInterFrame.class.getResource("/images/cancel_close_delete_reject_remove_16px_1225515_easyicon.net.png")));
		GroupLayout groupLayout = new GroupLayout(getContentPane());
		groupLayout.setHorizontalGroup(
			groupLayout.createParallelGroup(Alignment.LEADING)
				.addGroup(Alignment.TRAILING, groupLayout.createSequentialGroup()
					.addGroup(groupLayout.createParallelGroup(Alignment.TRAILING)
						.addGroup(Alignment.LEADING, groupLayout.createSequentialGroup()
							.addGap(33)
							.addComponent(panel_1, GroupLayout.DEFAULT_SIZE, 718, Short.MAX_VALUE))
						.addGroup(Alignment.LEADING, groupLayout.createSequentialGroup()
							.addGap(221)
							.addComponent(btnNewButton_1)
							.addGap(104)
							.addComponent(button))
						.addGroup(groupLayout.createSequentialGroup()
							.addGap(33)
							.addComponent(panel, GroupLayout.PREFERRED_SIZE, 718, Short.MAX_VALUE))
						.addGroup(groupLayout.createSequentialGroup()
							.addGap(33)
							.addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 718, Short.MAX_VALUE)))
					.addContainerGap())
		);
		groupLayout.setVerticalGroup(
			groupLayout.createParallelGroup(Alignment.LEADING)
				.addGroup(groupLayout.createSequentialGroup()
					.addContainerGap()
					.addComponent(panel, GroupLayout.PREFERRED_SIZE, 74, GroupLayout.PREFERRED_SIZE)
					.addGap(18)
					.addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 182, GroupLayout.PREFERRED_SIZE)
					.addGap(18)
					.addComponent(panel_1, GroupLayout.PREFERRED_SIZE, 248, GroupLayout.PREFERRED_SIZE)
					.addGap(18)
					.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
						.addComponent(btnNewButton_1)
						.addComponent(button))
					.addContainerGap())
		);
		
		JLabel lblNewLabel_3 = new JLabel("编号：");
		
		idtxt = new JTextField();
		idtxt.setEditable(false);
		idtxt.setColumns(10);
		
		JLabel lblNewLabel_4 = new JLabel("图书名称：");
		
		bookNametxt = new JTextField();
		bookNametxt.setColumns(10);
		
		JLabel lblNewLabel_5 = new JLabel("作者性别：");
		
		manjrb = new JRadioButton("男");
		buttonGroup.add(manjrb);
		manjrb.setSelected(true);
		
		femalejrb = new JRadioButton("女");
		buttonGroup.add(femalejrb);
		
		JLabel label = new JLabel("价格：");
		
		pricetxt = new JTextField();
		pricetxt.setColumns(10);
		
		JLabel label_1 = new JLabel("图书作者：");
		
		authortxt = new JTextField();
		authortxt.setColumns(10);
		
		JLabel lblNewLabel_6 = new JLabel("图书类别：");
		
		bookTypejcb = new JComboBox();
		
		JLabel label_2 = new JLabel("图书描述：");
		
		 bookDesctxt = new JTextArea();
		GroupLayout gl_panel_1 = new GroupLayout(panel_1);
		gl_panel_1.setHorizontalGroup(
			gl_panel_1.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel_1.createSequentialGroup()
					.addGap(32)
					.addGroup(gl_panel_1.createParallelGroup(Alignment.LEADING)
						.addGroup(gl_panel_1.createSequentialGroup()
							.addComponent(label_2)
							.addPreferredGap(ComponentPlacement.RELATED)
							.addComponent(bookDesctxt, GroupLayout.PREFERRED_SIZE, 525, GroupLayout.PREFERRED_SIZE))
						.addGroup(gl_panel_1.createSequentialGroup()
							.addGroup(gl_panel_1.createParallelGroup(Alignment.LEADING)
								.addGroup(gl_panel_1.createSequentialGroup()
									.addComponent(lblNewLabel_3)
									.addGap(18)
									.addComponent(idtxt, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
								.addGroup(gl_panel_1.createSequentialGroup()
									.addComponent(label)
									.addGap(18)
									.addComponent(pricetxt, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)))
							.addGap(35)
							.addGroup(gl_panel_1.createParallelGroup(Alignment.LEADING, false)
								.addGroup(gl_panel_1.createSequentialGroup()
									.addComponent(lblNewLabel_4)
									.addGap(18)
									.addComponent(bookNametxt, GroupLayout.PREFERRED_SIZE, 118, GroupLayout.PREFERRED_SIZE))
								.addGroup(gl_panel_1.createSequentialGroup()
									.addComponent(label_1)
									.addGap(18)
									.addComponent(authortxt)))
							.addPreferredGap(ComponentPlacement.UNRELATED)
							.addGroup(gl_panel_1.createParallelGroup(Alignment.LEADING)
								.addGroup(gl_panel_1.createSequentialGroup()
									.addComponent(lblNewLabel_5)
									.addPreferredGap(ComponentPlacement.UNRELATED)
									.addComponent(manjrb)
									.addGap(18)
									.addComponent(femalejrb))
								.addGroup(gl_panel_1.createSequentialGroup()
									.addComponent(lblNewLabel_6)
									.addPreferredGap(ComponentPlacement.UNRELATED)
									.addComponent(bookTypejcb, GroupLayout.PREFERRED_SIZE, 128, GroupLayout.PREFERRED_SIZE)))))
					.addContainerGap(48, Short.MAX_VALUE))
		);
		gl_panel_1.setVerticalGroup(
			gl_panel_1.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel_1.createSequentialGroup()
					.addGap(25)
					.addGroup(gl_panel_1.createParallelGroup(Alignment.BASELINE)
						.addComponent(lblNewLabel_3)
						.addComponent(idtxt, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(lblNewLabel_4)
						.addComponent(bookNametxt, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(lblNewLabel_5)
						.addComponent(manjrb)
						.addComponent(femalejrb))
					.addGap(18)
					.addGroup(gl_panel_1.createParallelGroup(Alignment.BASELINE)
						.addComponent(label)
						.addComponent(pricetxt, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(label_1)
						.addComponent(authortxt, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(lblNewLabel_6)
						.addComponent(bookTypejcb, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
					.addGap(18)
					.addGroup(gl_panel_1.createParallelGroup(Alignment.BASELINE)
						.addComponent(label_2)
						.addComponent(bookDesctxt, GroupLayout.PREFERRED_SIZE, 96, GroupLayout.PREFERRED_SIZE))
					.addContainerGap(66, Short.MAX_VALUE))
		);
		panel_1.setLayout(gl_panel_1);
		
		JLabel lblNewLabel = new JLabel("图书名称：");
		
		s_bookNametxt = new JTextField();
		s_bookNametxt.setColumns(10);
		
		JLabel lblNewLabel_1 = new JLabel("图书作者：");
		
		s_authortxt = new JTextField();
		s_authortxt.setColumns(10);
		
		JLabel lblNewLabel_2 = new JLabel("图书类别：");
		
		s_bookTypejcb = new JComboBox();
		
		JButton btnNewButton = new JButton("查询");
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				bookSearchActionPerformed(e);
			}
		});
		GroupLayout gl_panel = new GroupLayout(panel);
		gl_panel.setHorizontalGroup(
			gl_panel.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel.createSequentialGroup()
					.addContainerGap()
					.addComponent(lblNewLabel)
					.addPreferredGap(ComponentPlacement.RELATED)
					.addComponent(s_bookNametxt, GroupLayout.PREFERRED_SIZE, 103, GroupLayout.PREFERRED_SIZE)
					.addGap(18)
					.addComponent(lblNewLabel_1)
					.addPreferredGap(ComponentPlacement.RELATED)
					.addComponent(s_authortxt, GroupLayout.PREFERRED_SIZE, 104, GroupLayout.PREFERRED_SIZE)
					.addGap(19)
					.addComponent(lblNewLabel_2)
					.addPreferredGap(ComponentPlacement.RELATED)
					.addComponent(s_bookTypejcb, GroupLayout.PREFERRED_SIZE, 120, GroupLayout.PREFERRED_SIZE)
					.addPreferredGap(ComponentPlacement.RELATED)
					.addComponent(btnNewButton, GroupLayout.PREFERRED_SIZE, 71, GroupLayout.PREFERRED_SIZE)
					.addContainerGap(56, Short.MAX_VALUE))
		);
		gl_panel.setVerticalGroup(
			gl_panel.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel.createSequentialGroup()
					.addContainerGap()
					.addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
						.addComponent(lblNewLabel)
						.addComponent(s_bookNametxt, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(lblNewLabel_1)
						.addComponent(s_authortxt, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(lblNewLabel_2)
						.addComponent(s_bookTypejcb, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(btnNewButton))
					.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
		);
		panel.setLayout(gl_panel);
		
		bookTable = new JTable();
		bookTable.addMouseListener(new MouseAdapter() {
			@Override
			public void mousePressed(MouseEvent me) {
				bookTableMousePressed(me);
			}
		});
		bookTable.setModel(new DefaultTableModel(
			new Object[][] {
			},
			new String[] {
				"\u7F16\u53F7", "\u56FE\u4E66\u540D\u79F0", "\u56FE\u4E66\u4F5C\u8005", "\u4F5C\u8005\u6027\u522B", "\u56FE\u4E66\u4EF7\u683C", "\u56FE\u4E66\u7C7B\u522B", "\u56FE\u4E66\u63CF\u8FF0"
			}
		) {
			boolean[] columnEditables = new boolean[] {
				false, false, false, false, false, false, false
			};
			public boolean isCellEditable(int row, int column) {
				return columnEditables[column];
			}
		});
		bookTable.getColumnModel().getColumn(0).setPreferredWidth(57);
		bookTable.getColumnModel().getColumn(6).setPreferredWidth(131);
		scrollPane.setViewportView(bookTable);
		getContentPane().setLayout(groupLayout);
		

		bookDesctxt.setBorder(new LineBorder(new java.awt.Color(127,157,185),1,false));
		this.fillBookType("search");
		this.fillBookType("modify");
		this.fillTable(new Book());
	}
	private void bookDeleteActionPerformed(ActionEvent evt) {
		// TODO 自动生成的方法存根
		String id=idtxt.getText();
		if(StringUtil.isEmpty(id)){
			JOptionPane.showMessageDialog(null,"请选择要删除的记录");
			return;
		}
		int n=JOptionPane.showConfirmDialog(null,"确定要做删除操作吗？" );
		if(n==0){
			Connection con=null;
			try{
				con=dbUtil.getCon();
				int deleteNum=bookDao.delete(con, id);
				if(deleteNum==1){
					JOptionPane.showMessageDialog(null,"删除成功");
					this.resetValue();
					this.fillTable(new Book());
				}
				else JOptionPane.showMessageDialog(null,"删除失败");
			}
			catch(Exception e){
				e.printStackTrace();
				JOptionPane.showMessageDialog(null,"删除失败");
			}
			finally{
				try{
					dbUtil.closeCon(con);
				}
				catch(Exception e){
					e.printStackTrace();
					JOptionPane.showMessageDialog(null,"删除失败");
				}
			}
		}
	}

	private void bookUpdateActionPerformed(ActionEvent evt) {
		// TODO 自动生成的方法存根
		String id=idtxt.getText();
		if(StringUtil.isEmpty(id)){
			JOptionPane.showMessageDialog(null,"请选择要修改的记录");
			return;
		}
		String bookName=this.bookNametxt.getText();
		String bookDesc=this.bookDesctxt.getText();
		String author=this.authortxt.getText();
		String price =this.pricetxt.getText();
		if(StringUtil.isEmpty(id)){
			JOptionPane.showMessageDialog(null,"图书ID不能为空！");
			return;
		}
		if(StringUtil.isEmpty(bookName)){
			JOptionPane.showMessageDialog(null,"图书名称不能为空！");
			return;
		}
		if(StringUtil.isEmpty(author)){
			JOptionPane.showMessageDialog(null,"图书作者不能为空！");
			return;
		}
		if(StringUtil.isEmpty(price)){
			JOptionPane.showMessageDialog(null,"图书价格不能为空！");
			return;
		}
		String sex="";
		if(manjrb.isSelected()){
			sex="男";
			
		}
		else if(femalejrb.isSelected()){
			sex="女";
			
		}
		BookType bookType=(BookType) bookTypejcb.getSelectedItem();
		int bookTypeId=bookType.getId();
		Book book=new Book(Integer.parseInt(id), bookName,author,sex, bookTypeId , Float.parseFloat(price),bookDesc);
		
		Connection con=null;
		try{
			con=dbUtil.getCon();
			int modifyNum=bookDao.update(con, book);
			if(modifyNum==1){
				JOptionPane.showMessageDialog(null,"修改成功");
				this.resetValue();
				this.fillTable(new Book());
				
			}
			else JOptionPane.showMessageDialog(null,"修改失败");
		}
		catch(Exception e){
			e.printStackTrace();
			JOptionPane.showMessageDialog(null,"修改失败");
		}
		finally{
			try{
				dbUtil.closeCon(con);
			}catch(Exception e){
				e.printStackTrace();
				JOptionPane.showMessageDialog(null,"修改失败");
			}
		}
		
	}

	private void resetValue() {
		// TODO 自动生成的方法存根
		this.idtxt.setText("");
		this.bookNametxt.setText("");
		this.authortxt.setText("");
		this.pricetxt.setText("");

		this.manjrb.setSelected(true);
		this.bookDesctxt.setText("");
		if(this.bookTypejcb.getItemCount()>0){
			this.bookTypejcb.setSelectedIndex(0);
		}
	}
	/**
	 * 表格行点击事件处理
	 * @param me
	 */
	private void bookTableMousePressed(MouseEvent me) {
		// TODO 自动生成的方法存根
		int row=bookTable.getSelectedRow();
		this.idtxt.setText((String)bookTable.getValueAt(row,0));
		this.bookNametxt.setText((String)bookTable.getValueAt(row,1));
		this.authortxt.setText((String)bookTable.getValueAt(row,2));
		String sex=(String)bookTable.getValueAt(row,3);	
		if("男".equals(sex))
			this.manjrb.setSelected(true);
		else if("女".equals(sex))
			this.femalejrb.setSelected(true);
		this.pricetxt.setText((Float)bookTable.getValueAt(row,4)+"");
		String bookTypeName=(String)this.bookTable.getValueAt(row,5);
		int count=this.bookTypejcb.getItemCount();
		for (int i = 0; i < count; i++) {
			BookType item=(BookType)this.bookTypejcb.getItemAt(i);
			if(item.getBookTypeName().equals(bookTypeName)){
				this.bookTypejcb.setSelectedIndex(i);
			}
		}

		this.bookDesctxt.setText((String)bookTable.getValueAt(row,6));
	}

	/**
	 * 图书查询事件处理
	 * @param e
	 */
	private void bookSearchActionPerformed(ActionEvent evt) {
		// TODO 自动生成的方法存根
		String bookName=this.s_bookNametxt.getText();
		String author=this.s_authortxt.getText();
		BookType bookType=(BookType)this.s_bookTypejcb.getSelectedItem();
		int bookTypeId=bookType.getId();
		Book book=new Book(bookName, author, bookTypeId);
		this.fillTable(book);
	}

	/**
	 * 初始化下拉框
	 * @param type 下拉框类型
	 */
	private void fillBookType(String type){
		Connection con=null;
		BookType bookType=null;
		try{
			con=dbUtil.getCon();
			ResultSet rs=bookTypeDao.list(con, new BookType());
			if("search".equals(type)){
				bookType=new BookType();
				bookType.setBookTypeName("请选择");
				bookType.setId(-1); 
				this.s_bookTypejcb.addItem(bookType);
			}
			while(rs.next()){
				bookType=new BookType();
				bookType.setBookTypeName(rs.getString("bookTypeName"));
				bookType.setId(rs.getInt("id")); 
				if("search".equals(type)){

					this.s_bookTypejcb.addItem(bookType);
				}
				else if("modify".equals(type)){
					this.bookTypejcb.addItem(bookType);
				}
			}
		}
		catch(Exception e){
			e.printStackTrace();
		}
		finally{
			try {
				dbUtil.closeCon(con);
			} catch (Exception e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
		}
	}
	/**
	 * 初始化表格数据
	 * @param book
	 */
	private void fillTable(Book book){
		DefaultTableModel dtm= (DefaultTableModel) bookTable.getModel();
		dtm.setRowCount(0);
		Connection con=null;
		try{
			con=dbUtil.getCon();
			ResultSet rs=bookDao.list(con, book);
			while(rs.next()){
				Vector v=new Vector();
				v.add(rs.getString("id"));
				v.add(rs.getString("bookName"));
				v.add(rs.getString("author"));
				v.add(rs.getString("sex"));
				v.add(rs.getFloat("price"));
				v.add(rs.getString("bookTypeName"));
				v.add(rs.getString("bookDesc"));
				dtm.addRow(v);
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			try {
				dbUtil.closeCon(con);
			} catch (Exception e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
		}
	}
}
